<?php
header('Content-Type: application/json');
header('Cache-Control: no-cache');

$txtUrl = $_GET['txtUrl'] ?? '';

if (empty($txtUrl)) {
    echo json_encode(['error' => 'TXT文件URL不能为空']);
    exit;
}

// 获取TXT文件内容
$content = @file_get_contents($txtUrl);
if ($content === false) {
    echo json_encode(['error' => '无法读取TXT文件']);
    exit;
}

// 解析内容
$lines = explode("\n", $content);
$currentGroup = '';
$channels = [];
$totalLines = 0; // 用于统计实际的频道数量

foreach ($lines as $line) {
    $line = trim($line);
    if (empty($line)) continue;
    
    if (strpos($line, '#genre#') !== false) {
        $currentGroup = explode(',', $line)[0];
        continue; // 跳过分组行，不计入总数
    }
    
    $parts = explode(',', $line);
    if (count($parts) >= 2) {
        $channels[] = [
            'group' => $currentGroup,
            'name' => $parts[0],
            'url' => $parts[1]
        ];
        $totalLines++; // 只统计实际的频道行
    }
}

// 返回结果时包含实际的频道数量
echo json_encode([
    'channels' => $channels,
    'total' => $totalLines
]); 